<template>
    <div class="project-management-container">
        <div class="pmc-head">
            <div class="pmc-small-head">
                <img src="../assets/Picture/ProjectManagement/box.png" alt=" " class="pmc-box">
                <h2>项目管理</h2>
            </div>
            <button class="pmc-small-right-head">
                <span @click="openCreateDialog">新建项目</span>
            </button>
        </div>

        <div class="pmc-body">
            <div class="pmc-ul" v-if="projects && projects.length > 0">
                <div v-for="project in projects" :key="project.id" class="pmc-item">
                    <div class="pmc-item-container">
                        <div class="pmc-left-item">
                            <div class="pmc-image"><img src="../assets/Picture/ProjectManagement/document.png" alt=" ">
                            </div>
                            <div class="pmc-name">{{ project.name }}</div>
                        </div>
                        <div class="pmc-right-item">
                            <div class="pmc-date">{{ project.formattedDate }}
                            </div>
                            <div class="pmc-btn">
                                <el-button type="primary" size="small" class="el-button-1"
                                    @click="navigateToDocumentManagementView(project)">打开项目</el-button>
                                <el-button type="info" size="small" class="el-button-2"
                                    @click="showProjectDetails(project)">项目详情</el-button>
                                <el-button type="danger" size="small" class="el-button-3"
                                    @click="deleteProject(project)">删除项目</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else class="empty-project-message">
                <img src="../assets/Picture/ProjectManagement/emptybox.png" alt=" " class="empty-box blurred">
                <p class="blurred">项目列表为空，快去新建一个项目吧！</p>
            </div>
        </div>
        <!-- 添加新建模态窗口 -->
        <el-dialog v-model="dialogVisible" title="新建项目" width="60%" :close-on-click-modal="false">
            <el-form label-width="100px">
                <el-form-item label="项目名称" required>
                    <el-input v-model="newProject.name" placeholder="请输入项目名称"></el-input>
                </el-form-item>
                <el-form-item label="项目描述">
                    <el-input v-model="newProject.description" type="textarea" rows="4"
                        placeholder="请输入项目描述"></el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="createProject" :loading="submitLoading">
                        创建
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 添加查看详情窗口 -->
        <transition name="fade">
            <div class="project-detail-modal" v-if="showProjectDetailModal">
                <div class="create-project-modal-content">
                    <div class="cpc-head">
                        <h3>项目详情</h3>
                        <img src="../assets/Picture/ProjectManagement/x.png" alt=" " class="cpc-x"
                            @click="toggleProjectDetailModal">
                    </div>
                    <div class="pdm-body">
                        <div class="project-name">
                            <div class="projectName">项目名称*</div>
                            <input type="text" v-model="currentProject.name">
                        </div>
                        <div class="project-description">
                            <div class="projectDescription">项目描述</div>
                            <textarea v-model="currentProject.description"></textarea>
                        </div>
                        <div class="project-created-at">
                            <div class="p-creat-time">项目创建时间</div>
                            <input type="text" v-model="currentProject.createdAt" disabled class="project-crated-input">
                        </div>
                        <div class="project-updated-at">
                            <div class="p-update-time">项目更新时间</div>
                            <input type="text" v-model="currentProject.updatedAt" disabled
                                class="project-updated-input">
                        </div>
                    </div>

                    <div class="buttons">
                        <button @click="toggleProjectDetailModal">关闭</button>
                        <button @click="updateProjectDetail">更新项目详情</button>
                    </div>
                </div>
            </div>
        </transition>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from '@/plugins/axios'
import { ElMessage } from 'element-plus'
import { useEditorStore } from '@/store/editor'

const route = useRoute()
const router = useRouter()
const projectName = ref('')
const projects = ref([])
const store = useEditorStore()

const getProjectList = async () => {
    try {
        const response = await axios.post('/get_project_list', {
            email: localStorage.getItem('userEmail')
        })
        console.log('获取项目列表成功:', response.data.data)
        if (Array.isArray(response.data.data) && response.data.data.length > 0) {
            const projectList = response.data.data.map(project => ({
                ...project,
                id: project.id,
                formattedDate: formatDate(new Date(project.createdAt).getTime())
            }))

            projects.value = projectList
        } else {
            console.log('项目列表为空')
            // 提示用户项目列表为空
            projects.value = []
        }
        console.log('projects.value:', projects.value)
    } catch (error) {
        ElMessage.error('获取项目列表失败:', error)
    }
}

onMounted(async () => {
    // 确保有 token 才发起请求
    if (!store.getUserToken) {
        ElMessage.warning('请先登录')
        await router.push('/login')
        return
    }
    await getProjectList()
    const param = route.params.projectName
    if (Array.isArray(param)) {
        projectName.value = param.join(', ')
    } else if (typeof param === 'string') {
        projectName.value = param
    } else {
        projectName.value = '未定义项目名称' // 添加默认值
    }
})

// 控制模态窗口的显示和隐藏
// const showCreateProjectModal = ref(false)
const showProjectDetailModal = ref(false)

// 新项目表单数据
// const newProjectName = ref('1')
// const newProjectDescription = ref('1')

// 当前项目详情
const currentProject = ref({})

// 新增项目对话框相关状态
const dialogVisible = ref(false)
const newProject = reactive({
    name: '',
    description: ''
})
const submitLoading = ref(false)

// 显示项目详情模态框
const showProjectDetails = (project) => {
    console.log('项目详情:', project)
    currentProject.value = { ...project }
    toggleProjectDetailModal()
}

// 更新项目详情
const updateProjectDetail = async () => {
    try {
        // 假设 currentProject 包含项目的 id, name, 和 description
        const response = await axios.put(`/update_project/${currentProject.value.id}`, {
            name: currentProject.value.name,
            description: currentProject.value.description
        });

        // 处理响应
        if (response.data.code === 200 && response.data.data > 0) {
            ElMessage.success('项目详情更新成功');
            // 更新项目列表或其他相关状态
            await getProjectList();
        } else {
            ElMessage.error('项目详情更新失败，请稍后重试');
        }
    } catch (error) {
        console.error('更新项目详情失败:', error);
        ElMessage.error('更新项目详情请求失败，请检查网络连接');
    }
}

const toggleProjectDetailModal = () => {
    showProjectDetailModal.value = !showProjectDetailModal.value
}

// 打开新建项目对话框
const openCreateDialog = () => {
    dialogVisible.value = true
}

// 创建新项目
const createProject = async () => {
    // 表单验证
    if (!newProject.name.trim()) {
        ElMessage.warning('项目名称不能为空')
        return
    }

    submitLoading.value = true
    try {
        console.log('创建新项目:', newProject)
        // 发送创建项目请求
        const response = await axios.post('/create_project', {
            email: localStorage.getItem('userEmail'),
            name: newProject.name,
            description: newProject.description
        })

        // 处理响应
        if (response.data.code === 200) {
            ElMessage.success(response.data.msg)
            dialogVisible.value = false
            // 刷新项目列表
            await getProjectList()
        } else {
            ElMessage.error('项目创建失败，请稍后重试')
        }
    } catch (error) {
        console.error('创建项目失败:', error)
        ElMessage.error('创建项目请求失败，请检查网络连接')
    } finally {
        submitLoading.value = false
    }
}

// 格式化日期
const formatDate = (timestamp) => {
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}/${month}/${day} :${hours}:${minutes}:${seconds}`
}

const navigateToDocumentManagementView = (project) => {
    console.log('打开项目:', project.name, '项目ID:', project.id, '项目描述:', project.description)
    // 导航到文档管理页面，并传递项目ID和项目名称
    router.push({
        name: 'DocumentManagement',
        params: { projectId: project.id, projectName: project.name, projectDescription: project.description }
    })
}

// 删除项目
const deleteProject = async (project) => {
    console.log('要删除的项目对象：', project); // 打印整个项目对象
    console.log('要删除的项目id：', project.id); // 打印项目ID
    try {
        const response = await fetch(`/project/delete/${project.id}`, {
            method: 'DELETE'
        });
        const data = await response.json();
        if (data.success) {
            ElMessage.success('项目删除成功' || data.message);
            // 从项目列表中删除项目
            projects.value = projects.value.filter(proj => proj.id !== project.id);
        } else {
            ElMessage.error('项目删除失败' || data.message);
        }
    } catch (error) {
        console.error('删除项目失败:', error);
        ElMessage.error('删除项目请求失败，请检查网络连接');
    }
};
</script>

<style scoped>
*,
*:before,
*:after {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

.project-management-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    height: 100vh;
    width: 100%;
    background-color: #f5f5f5;
}

.pmc-head {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    background: #ffffff;
    width: 100%;
    padding: 20px;
    border-bottom: 1px solid rgb(247, 247, 247);
    border-radius: 10px;
    user-select: none;
}

.pmc-box {
    width: 30px;
    height: 30px;
    object-fit: contain;
}

.pmc-small-head {
    display: flex;
    justify-content: center;
    align-items: center;
}

.pmc-small-head h2 {
    font-family: 'Arial', sans-serif;
    /* 字体系列 */
    font-size: 24px;
    /* 字体大小 */
    font-weight: bold;
    /* 加粗 */
    color: #333333;
    /* 字体颜色 */
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
    /* 阴影效果 */
    text-decoration: none;
    /* 去掉下划线 */
    transition: color 0.3s ease;
    /* 过渡效果 */
}

.pmc-small-head h2:hover {
    color: #007BFF;
    /* 鼠标悬停时的颜色 */
}

.pmc-small-right-head {
    display: flex;
    justify-content: center;
    align-items: center;
}

.pmc-small-left-head span {
    padding-left: 10px;
}

.pmc-body {
    background: #ffffff;
    width: 100%;
    height: 90%;
    padding: 20px;
    border-bottom: 1px solid rgb(247, 247, 247);
    border-radius: 10px;
    user-select: none;
}

.empty-project-message {
    width: 100%;
    height: 90%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.empty-box {
    width: 150px;
    height: 150px;
    object-fit: contain;
    margin-bottom: 30px;
}

.blurred {
    filter: grayscale(100%);
    opacity: 0.2;
    /* 可选：调整透明度 */
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    margin-bottom: 10px;
}

.create-project-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
}

.create-project-modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    width: 80%;
    max-width: 600px;
}

.cpc-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: 'Arial', sans-serif;
    /* 字体系列 */
    font-size: 18px;
    /* 字体大小 */
    font-weight: bold;
    /* 加粗 */
    color: #333333;
    /* 字体颜色 */
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
    /* 阴影效果 */
    text-decoration: none;
    /* 去掉下划线 */
    transition: color 0.3s ease;
    /* 过渡效果 */
}

.cpc-head h3:hover {
    color: #007BFF;
    /* 鼠标悬停时的颜色 */
}

.cpc-x {
    width: 20px;
    height: 20px;
    object-fit: contain;
}

.project-name,
.project-description {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0px 20px 0px;
    font-family: 'Arial', sans-serif;
    /* 字体系列 */
    font-size: 15px;
    /* 字体大小 */
    color: #555555;
    /* 字体颜色 */
    text-decoration: none;
    /* 去掉下划线 */
    transition: color 0.3s ease;
}

.project-name input {
    display: inline-block;
    width: 100%;
    min-height: 50px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
    overflow-y: auto;
}

.project-description textarea {
    display: inline-block;
    width: 100%;
    min-height: 50px;
    min-width: 85%;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
    overflow-y: auto;
}

.projectName,
.projectDescription {
    width: 15%;
    margin-right: 10px;
}

.buttons {
    display: flex;
    justify-content: flex-end;
}

.buttons button {
    margin-left: 10px;
}

.buttons button:first-child {
    background-color: #f6f6f6;
    color: #262626;
}

.buttons button:first-child:hover {
    background-color: #cccccc;
}

button {
    padding: 10px 20px;
    background-color: #333333;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #666666;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

.pmc-item-container {
    width: 100%;
    height: 30px;
    display: flex;
    justify-content: space-between;
    align-items: start;
    margin-top: 10px;
    padding-bottom: 10px;
}

.pmc-item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: start;
    margin-top: 10px;
    padding-bottom: 10px;
}

.pmc-left-item {
    display: flex;
    justify-content: start;
    align-items: center;
}

.pmc-right-item {
    display: flex;
    justify-content: space-between;
    align-items: end;
}

.pmc-image img {
    width: 20px;
    height: 20px;
    object-fit: contain;

}

.pmc-image {
    margin: 0px 5px 0px 0px;
}

.pmc-name {
    font-family: 'Arial', sans-serif;
    /* 字体系列 */
    font-size: 14px;
    /* 字体大小 */
    font-weight: bold;
    /* 加粗 */
    color: #333333;
    /* 字体颜色 */
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
    /* 阴影效果 */
    text-decoration: none;
    /* 去掉下划线 */
    transition: color 0.3s ease;
    /* 过渡效果 */
    margin-left: 5px;
    margin-right: 20px;
    padding-bottom: 3px;
}

.pmc-description {
    font-family: 'Arial', sans-serif;
    /* 字体系列 */
    font-size: 10px;
    /* 字体大小 */
    color: #666666;
    /* 字体颜色 */
    text-decoration: none;
    /* 去掉下划线 */
    margin: 0px 0px 0px 0px;
}

.pmc-date {
    font-family: 'Arial', sans-serif;
    /* 字体系列 */
    font-size: 10px;
    /* 字体大小 */
    color: #666666;
    /* 字体颜色 */
    text-decoration: none;
    /* 去掉下划线 */
    padding: 0px 5px 3px 5px;
}

.el-button-1 {
    background-color: #4caf50;
    border-color: #4caf50;
    margin-left: 20px;
}

.el-button-2 {
    background-color: #909399;
    border-color: #909399;

}

.el-button-3 {
    background-color: #F56C6C;
    border-color: #F56C6C;

}

.project-detail-modal {
    display: flex;
    /* 或其他合适的显示方式 */
    position: fixed;
    justify-content: center;
    align-items: center;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
}

.project-detail-modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 8px;
}

.project-created-at,
.project-updated-at {
    width: 100%;
    display: flex;
    justify-content: start;
    align-items: center;
    margin: 20px 0px 20px 0px;

    font-family: 'Arial', sans-serif;
    /* 字体系列 */
    font-size: 15px;
    /* 字体大小 */
    color: #555555;
    /* 字体颜色 */
    text-decoration: none;
    /* 去掉下划线 */
    transition: color 0.3s ease;
}

.p-creat-time,
.p-update-time {
    margin-right: 10px;
}

.project-crated-input,
.project-updated-input {
    width: 82%;
    cursor: not-allowed;
}
</style>
